<?php

namespace app\api\controller;

use app\api\dao\WeChatZftDao;
use app\api\model\WeChatMerchant as WeChatMerchantModel;
use app\api\validate\WeChatMerchantValidator;
use app\service\UploadFileService;

/**
 * 微信商户控制器（兼容版本）
 */
class WeChatMerchant extends Base
{
    private $dao;
    private $validator;

    /**
     * 初始化
     */
    protected function initialize(): void
    {
        parent::initialize();
        $this->dao = new WeChatZftDao(0);
        $this->validator = new WeChatMerchantValidator();
    }

    protected function getDao(): WeChatZftDao
    {
        return $this->dao;
    }

    protected function getValidator(): WeChatMerchantValidator
    {
        return $this->validator;
    }

    /**
     * 商户列表
     */
    public function list()
    {
        try {
            [$page, $pageSize] = $this->getPaginationParams();
            $where['openid'] = $this->getOpenid();
            $result = $this->getDao()->getPagesLists($where, $page, $pageSize);
            if ($result) {
                foreach ($result['data'] as &$value) {
                    if (in_array($value['status'], [
                        WeChatMerchantModel::STATUS['SUBMITTED'],
                        WeChatMerchantModel::STATUS['TO_BE_SIGNED'],
                        WeChatMerchantModel::STATUS['TO_BE_CONFIRMED']
                    ])) {
                        $value = $this->getDao()->getApplyStatus($value);
                    }
                    $value = $this->getDao()->getTranslate($value);
                }
            }
            $this->logOperation('merchant_list', ['page' => $page, 'page_size' => $pageSize]);
            return $this->success($result);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 商户详情
     */
    public function details($id)
    {
        try {
            $data = $this->getDao()->getDetails($id);

            if (in_array($data['status'], [
                WeChatMerchantModel::STATUS['SUBMITTED'],
                WeChatMerchantModel::STATUS['TO_BE_SIGNED'],
                WeChatMerchantModel::STATUS['TO_BE_CONFIRMED']
            ])) {
                $data = $this->getDao()->getApplyStatus($data);
            }
            $result = $this->getDao()->getTranslate($data);
            $this->logOperation('merchant_detail', ['id' => $id]);
            return $this->success($result);

        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 添加商户
     */
    public function add()
    {
        try {
            $post = $this->request->post();
            $post['openid'] = $this->getOpenid();

            // 验证提交的数据
            $validate = $this->getValidator();
            if (!$validate->add($post)) {
                return $this->error($validate->getError());
            }

            $result = $this->getDao()->add($post);

            $this->logOperation('merchant_create', ['result' => $result]);

            return $this->success($result, '商户信息保存成功');

        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 编辑商户
     */
    public function edit($id)
    {
        try {
            $post = $this->request->post();
            $post['openid'] = $this->getOpenid();

            // 验证提交的数据
            $validate = $this->getValidator();
            if (!$validate->add($post)) {
                return $this->error($validate->getError());
            }

            $result = $this->getDao()->edit($id, $post);

            $this->logOperation('merchant_update', ['id' => $id]);

            return $this->success($result, '商户信息更新成功');

        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 图片上传
     */
    public function uploadImage()
    {
        try {
            $post = $this->request->post();
            $path = 'wechat/merchant/';
            $uploadFileService = new UploadFileService($path);

            // 启用图片压缩功能
            $info = $uploadFileService->uploadOssFile('file', true);
            if (!isset($info['dir']) || empty($info['dir'])) {
                return $this->error('图片上传失败');
            }

            // 图片识别并获取图片编码
            $result = $this->getDao()->imageOcrAndCode($info['dir'], $post['type']);
            
            // 添加压缩信息到结果中
            if (isset($info['compression_info'])) {
                $result['compression_info'] = $info['compression_info'];
            }

            $logData = [
                'type' => $post['type'], 
                'url' => $info['dir']
            ];
            
            // 记录压缩信息到日志
            if (isset($info['compression_info']) && $info['compression_info']['compressed']) {
                $logData['compression'] = [
                    'original_size' => $info['compression_info']['original_size'],
                    'final_size' => $info['compression_info']['final_size'],
                    'compression_ratio' => $info['compression_info']['compression_ratio'] . '%',
                    'quality' => $info['compression_info']['quality']
                ];
            }
            
            $this->logOperation('image_upload', $logData);

            return $this->success($result, '图片上传成功');

        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 银行列表
     */
    public function bankList()
    {
        try {
            $data = [
                '工商银行', '交通银行', '招商银行', '民生银行', '中信银行',
                '浦发银行', '兴业银行', '光大银行', '广发银行', '平安银行',
                '北京银行', '华夏银行', '农业银行', '建设银行', '邮政储蓄银行',
                '中国银行', '宁波银行', '其他银行'
            ];

            return $this->success($data);

        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 银行支行查询
     */
    public function bankAccount()
    {
        try {
            $param = $this->request->param();
            if (empty($param['name'])) {
                return $this->error('请传入开户行名称');
            }

            $account = $this->getDao()->bankAccount($param);

            return $this->success($account);

        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 组织机构列表
     */
    public function orgList()
    {
        try {
            $orgList = $this->getDao()->orgList();

            return $this->success($orgList);

        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 行业列表
     */
    public function industryList()
    {
        try {
            $industryList = $this->getDao()->industryList();

            return $this->success($industryList);

        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 设置收款账户
     */
    public function setReceivingAccount($id)
    {
        try {
            $isPayAccount = $this->request->post('is_pay_account');

            if (!$id) {
                return $this->error('参数错误');
            }

            $result = $this->getDao()->setReceivingAccount($id, $isPayAccount);

            $this->logOperation('set_receiving_account', [
                'merchant_id' => $id,
                'is_pay_account' => $isPayAccount
            ]);

            return $this->success($result, '收款账户设置成功');

        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }
}
